<?php
namespace common\bonus;
use common\models\TeamTotalLog;
use common\models\TeamTotal as TeamTotalModel;
use common\utils\CommonFun;
/*
	累计团队业绩
*/
class TeamTotal
{

	public static function bonusAction($params)
	{

		if(!$params['uper']) return false;

		foreach($params['uper'] as $level=>$member)
		{ 
			//添加日志
			$flag1 = self::addTeamTotalLog($params,$member,$level);
			if(!$flag1) CommonFun::writeLog('[累计业绩日志添加失败]，member_id:'.$member['member_id'].'data:'.json_encode($params),'bonus');

			//累计业绩
			$flag2 = self::addTeamTotal($params,$member,$level);
			if(!$flag2) CommonFun::writeLog('[累计业绩失败]，member_id:'.$member['member_id'].'data:'.json_encode($params),'bonus');
		}
		return ['state'=>true,'msg'=>'success'];
	}


	//累计
	private static function addTeamTotal($params, $member, $level)
	{
		$teamModel = TeamTotalModel::find()->where(['member_id' => $member['member_id']])->one();
		
		if($teamModel)
		{
			$teamModel->total += $params['money'];
			if($level>0)
				$teamModel->team_total += $params['money'];
			else
				$teamModel->my_total += $params['money'];
			return $teamModel->save();
		}else
		{
			$teamModel = new TeamTotalModel();
			$teamModel->member_id = $member['member_id'];
			$teamModel->invite_id = $member['invite_id'];
			$teamModel->total = $params['money'];
			$teamModel->mch_id = MCHID;

			if($level>0)
				$teamModel->team_total = $params['money'];
			else
				$teamModel->my_total = $params['money'];

			return $teamModel->save();
		}
	}


	//日志记录
	private static function addTeamTotalLog($params,$member,$level)
	{
		$model = new TeamTotalLog;
		$model->member_id = $member['member_id'];
		$model->money = $params['money'];
		$model->source_id = $params['source_id'];
		$model->from_member_id = $params['member_id'];
		$model->level = $level;
		$model->mch_id = MCHID;
		$model->create_time = time();
		return $model->save();
	}



		


}